<template>
  <div>
    <v-tooltip v-model="tooltipshow" bottom>
      <template v-slot:activator="{ on, attrs }">
        <v-btn text v-bind="attrs" v-on="on" @click="toggleInternationalLang(internationalIcon)">
          <svg-icon class="internationalIconClass" :icon-class="internationalIcon"></svg-icon>
        </v-btn>
      </template>
      <span>切换国际化语言</span>
    </v-tooltip>
    <v-snackbar v-model="snackbar" class="toggleLangSnackbar" top>
      {{ text + ' ' + currentLang + ', ' + $t('common.switch') + ': ' + toggleLang }}
      <template v-slot:action="{ attrs }">
        <!-- <v-btn color="error" text v-bind="attrs" @click="snackbar = false"> -->
        <v-btn color="error" text v-bind="attrs" @click="switchLanguage(toggleLang)">
          {{ $t('common.switch') }}
        </v-btn>
      </template>
    </v-snackbar>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import i18n from '@/i18n/i18'

export default {
  // toggle international language
  name: 'ToggleLanguage',

  data() {
    return {
      // dynamic internation icon
      internationalIcon: '',
      // tooltip show flag
      tooltipshow: false,
      // snackbar show flag
      snackbar: false,
      // toggle button title
      text: this.$t('i18.changeLang'),
      // current language
      currentLang: '',
      // toggle to lanuage
      toggleLang: ''
    }
  },

  computed: {
    ...mapGetters(['lang'])
  },

  watch: {
    lang(nv) {
      i18n.locale = nv
      this.internationalIcon = nv === 'zhHans' ? 'CN' : 'EN'
      this.currentLang = nv === 'zhHans' ? this.$t('i18.cn') : this.$t('i18.en')
      this.toggleLang = nv === 'zhHans' ? this.$t('i18.en') : this.$t('i18.cn')
      this.redirectPath()
    }
  },

  created() {
    this.internationalIcon = this.lang === 'zhHans' ? 'CN' : 'EN'
    this.currentLang = this.lang === 'zhHans' ? this.$t('i18.cn') : this.$t('i18.en')
    this.toggleLang = this.lang === 'zhHans' ? this.$t('i18.en') : this.$t('i18.cn')
  },

  methods: {
    toggleInternationalLang(icon) {
      this.snackbar = true
    },

    switchLanguage(toggleLang) {
      let lang = toggleLang
      if (lang === 'Chinese' || lang === this.$t('i18.cn')) {
        lang = 'zhHans'
      }
      lang === 'English' && (lang = 'en')
      this.$store.dispatch('i18n/setI18nLang', lang)
      this.snackbar = false
    },

    redirectPath() {
      this.$nextTick(() => {
        this.$router.replace({
          path: '/redirect' + this.$route.fullPath
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.internationalIconClass {
  width: 2em !important;
  height: 2em !important;
}

// .toggleLangSnackbar {
// top: 4em;
// }
</style>
